import { useState, useEffect } from 'react'
import { getLocation, openSetting, showModal } from 'remax/wechat'

export default () => {
  const [location, setLocation] = useState<WBG.Location>()

  const callback = async () => {
    try {
      const { longitude, latitude } = await getLocation({ type: 'gcj02' })
      setLocation({ longitude, latitude })
    } catch ({ errMsg }) {
      if (/auth deny/.test(errMsg)) {
        const { confirm } = await showModal({
          title: '获取位置失败',
          content: '请前往设置界面手动授权',
          showCancel: false,
        })
        confirm && (await openSetting())
        callback()
      }
    }
  }

  useEffect(() => {
    callback()
  }, [])

  return { location }
}
